package org.zxstudio.encrypt;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.zxstudio.encrypt.FileChildAdapter.onItemSelectedListener;
import org.zxstudio.encrypt.utils.LazyImageLoader;
import org.zxstudio.encrypt.utils.SDUtils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MediaBaseAdapter extends BaseAdapter {

	private static final String TAG = "FileBaseAdapater";
	private static final boolean DEBUG = true;

	public static final int VIEWMODE_LIST = 0;
	public static final int VIEWMODE_ICON = 1;

	private Context mContext;
	private List<MediaBean> mFiles = null;
	private final List<MediaBean> mSelectedFiles = new ArrayList<MediaBean>();

	private int mViewMode = VIEWMODE_ICON;

	private LazyImageLoader mLoader;

	private onItemSelectedListener mSelectedListener;

	public MediaBaseAdapter(Context context, List<MediaBean> files) {
		mContext = context;
		mFiles = files;
		mLoader = LazyImageLoader.getInstance();
	}

	@Override
	public int getCount() {
		if (mFiles != null) {
			return mFiles.size();
		}
		return 0;
	}

	@Override
	public MediaBean getItem(int position) {

		if ((position >= 0) && (position < this.getCount())) {
			return mFiles.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		GridHolder gridHolder = null;
		//if (convertView == null) {   //为了避免异步加载图片的问题
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.item_gridview, null);
			gridHolder = new GridHolder();
			gridHolder.fileIcon = (ImageView) convertView
					.findViewById(R.id.gridview_fileicon);
			gridHolder.fileName = (TextView) convertView
					.findViewById(R.id.gridview_filename);
			gridHolder.selectView = (ImageView) convertView
					.findViewById(R.id.check_icon);
			convertView.setTag(gridHolder);
	//	} else {
	//		gridHolder = (GridHolder) convertView.getTag();
	//	}

		MediaBean media = this.getItem(position);
		// gridHolder.selectView.setOnClickListener(new
		// SelectViewListener(position));
	/*	File f = new File(media.data);
		if (f != null) {*/
		/*	if (media.type == MediaDomain.IMAGE) {
				gridHolder.fileIcon.setImageResource(R.drawable.icon_image);
			mLoader.loadImage(gridHolder.fileIcon, media.data,
						mLoaderListener,MediaDomain.IMAGE);
			}
			if (media.type == MediaDomain.VIDEO) {
				gridHolder.fileIcon.setImageResource(R.drawable.icon_video);
				mLoader.loadVideo(gridHolder.fileIcon,media.data,
						mLoaderListener,MediaDomain.VIDEO);
			}*/
			if (media.type == MediaBean.AUDIO) {
				gridHolder.fileIcon.setImageResource(R.drawable.icon_audio);
			} else {
				mLoader.loadMedia(gridHolder.fileIcon, media.data, mLoaderListener, media.type);
			}
			
			gridHolder.fileName.setText(media.title);
		//}

		if (mSelectedFiles.contains(media)) {
			gridHolder.selectView
					.setBackgroundResource(R.drawable.btn_check_buttonless_on);
		} else {
			gridHolder.selectView
					.setBackgroundResource(R.drawable.btn_check_buttonless_off);
		}
		return convertView;
	}

	public int getViewMode() {
		return mViewMode;
	}

	public void setViewMode(int viewmode) {
		mViewMode = viewmode;
	}

	public int getFileIcon(File f) {
		int icon = 0;

		String str = org.zxstudio.encrypt.utils.Constant.getFileIcon(f);
		if (str == null) {
			icon = -1;
		} else {
			Resources res = mContext.getResources();
			icon = res
					.getIdentifier(str, "drawable", mContext.getPackageName());

			if (icon <= 0)
				icon = R.drawable.icon_file;
		}

		return icon;
	}

	public Drawable getApkIcon(String path) {
		PackageManager pm = mContext.getPackageManager();
		PackageInfo info = pm.getPackageArchiveInfo(path,
				PackageManager.GET_ACTIVITIES);
		if (info != null) {
			ApplicationInfo appInfo = info.applicationInfo;

			if (Build.VERSION.SDK_INT >= 8) {
				appInfo.sourceDir = path;
				appInfo.publicSourceDir = path;
			}

			return appInfo.loadIcon(pm);
		}
		return null;
	}

	public String getFileTime(long filetime) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String ftime = formatter.format(new Date(filetime));
		return ftime;
	}

	public String getFileSize(long filesize) {
		DecimalFormat df = new DecimalFormat("#.00");
		StringBuffer mstrbuf = new StringBuffer();

		if (filesize < 1024) {
			mstrbuf.append(filesize);
			mstrbuf.append(" B");
		} else if (filesize < 1048576) {
			mstrbuf.append(df.format((double) filesize / 1024));
			mstrbuf.append(" K");
		} else if (filesize < 1073741824) {
			mstrbuf.append(df.format((double) filesize / 1048576));
			mstrbuf.append(" M");
		} else {
			mstrbuf.append(df.format((double) filesize / 1073741824));
			mstrbuf.append(" G");
		}

		df = null;

		return mstrbuf.toString();
	}
	static class GridHolder {
		ImageView fileIcon;
		TextView fileName;
		ImageView selectView;
	}

	private LazyImageLoader.OnImageLoaderListener mLoaderListener = new LazyImageLoader.OnImageLoaderListener() {

		@Override
		public void onImageLoad(ImageView t, Drawable drawable, int mimeType) {
			if (DEBUG) {
				Log.v(TAG, "onImageLoad"+mimeType);
			}
			if (mimeType != MediaBean.AUDIO) {
				t.setImageDrawable(drawable);
			}  else {
				t.setImageResource(R.drawable.icon_audio);
			}
			
		}

		@Override
		public void onError(ImageView t) {
			if (DEBUG) {
				Log.v(TAG, "onError....................");
			}
		}

		@Override
		public void onImageLoad(ImageView t, Drawable drawable) {
			
		}

	};

	@Override
	public void notifyDataSetChanged() {
		super.notifyDataSetChanged();
		notifySelected();
	}

	/**
	 * 数据源发生变化
	 */
	public void notifyDataSourceChanged() {
		clearSelected();
		this.notifyDataSetChanged();
	}

	public void clearSelected() {
		mSelectedFiles.clear();
	}

	public List<MediaBean> getSelectedList() {
		return mSelectedFiles;
	}

	private class SelectViewListener implements View.OnClickListener {

		final int location;

		public SelectViewListener(int position) {
			location = position;
		}

		@Override
		public void onClick(View v) {
			if (DEBUG) {
				Log.v(TAG, "onClick:" + location);
			}
			MediaBean domain = getItem(location);
			if (domain != null) {
				if (mSelectedFiles.contains(domain)) {
					mSelectedFiles.remove(domain);
					v.setBackgroundResource(R.drawable.btn_check_buttonless_off);
				} else {
					mSelectedFiles.add(domain);
					v.setBackgroundResource(R.drawable.btn_check_buttonless_on);
				}
			}
			// MediaBaseAdapter.this.notifyDataSetChanged();
		}
	}

	public void updateSelectItem(View view, int location) {
		MediaBean domain = getItem(location);
		ImageView selectView = (ImageView)view.findViewById(R.id.check_icon);
		if (domain != null) {
			if (mSelectedFiles.contains(domain)) {
				mSelectedFiles.remove(domain);
				if (selectView != null)
					selectView.setBackgroundResource(R.drawable.btn_check_buttonless_off);
			} else {
				mSelectedFiles.add(domain);
				if (selectView != null)
					selectView.setBackgroundResource(R.drawable.btn_check_buttonless_on);
			}
		}
		notifySelected();
		// this.notifyDataSetChanged();
	}
	
	public void selectAllItem() {
		mSelectedFiles.containsAll(mFiles);
	}
	
	public void removeAllItem() {
		mSelectedFiles.removeAll(mFiles);
	}
	
	private void notifySelected() {
		if (mSelectedListener != null) {
			if (mSelectedFiles.size() > 0) {
				mSelectedListener.hasItemSelected();
			} else {
				mSelectedListener.noItemSelected();
			}
		}
	}

	public interface onItemSelectedListener {
		public void hasItemSelected();

		public void noItemSelected();
	};

	public void registerItemSelectListener(onItemSelectedListener listener) {
		mSelectedListener = listener;
	}

	public void unregisterItemSelectListener() {
		mSelectedListener = null;
	}

}
